<template>
  <el-upload class="avatar-uploader"
    action="#"
    :accept="accept"
    :show-file-list="false"
    :http-request="onUpload"
    :before-upload="beforeUpload">
    <img v-if="url"
      :src="url"
      class="avatar">
    <div v-else class="avatar-uploader-icon">
      <i class="el-icon-plus"></i>
      <p v-if="format.length == 1">上传{{ formatText }}格式图片</p>
      <p v-else style="line-height: 20px;margin-top: 8px;">支持图片格式：<br/>{{ formatText }}</p>
    </div>
  </el-upload>
</template>
<script>
import { uploadApi } from '@/api/rights/rights'
export default {
  name: 'ImgUpload',
  props: {
    url: {
      type: String,
      require: true
    },
    format: {
      type: Array,
      default () {
        return ['svg+xml']
      }
    }
  },
  model: {
    prop: 'url',
    event: 'input'
  },
  computed: {
    accept () {
      return this.format.map(v => `image/${v}`).join(',')
    },
    formatText () {
      return this.format.map(v => v === 'svg+xml' ? 'svg' : v).join(',')
    }
  },
  methods: {
    /** 图片上传成功处理 */
    onUpload ({ file, data = {} }) {
      const forms = new FormData()
      forms.append('file', file)
      uploadApi(forms).then(res => {
        const url = res.data?.url
        this.$emit('input', url)
      })
    },
    /** 图片上传之前处理 */
    beforeUpload (file) {
      const formatType = file.type.split('/')[1]
      if (this.format.includes(formatType)) return true
      this.msgError('上传图片只能是 ' + this.formatText + ' 格式!')
      return false
    }
  }
}
</script>
<style lang="scss">
.avatar-uploader .el-upload{
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  &:hover {
    border-color: #409eff;
  }
}
.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: #8c939d;
  width: 148px;
  height: 148px;
  text-align: center;
  i{
    font-size: 28px;
  }
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>
